package com.controller;

import com.json.Json;
import com.util.MyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("file")
public class UploadController {

    @PostMapping("/upload")
    public Map<String,Object> upload(HttpServletRequest request) {
        System.out.println("开始上传...");
        MultipartHttpServletRequest multipartRequest
                = (MultipartHttpServletRequest) request;

        MultipartFile mFile = multipartRequest.getFile("file");
        System.out.println(mFile.getOriginalFilename());
        String path = request.getSession().getServletContext().getRealPath("/upload");
        System.out.println("上传绝对路径是：" + path);
        try{
            String image = MyUtils.uploadFile(mFile,path); //image 表示上传成功之后的文件名
            System.out.println("文件上传成功！");
            System.out.println("文件名是：" + image);

            return Json.success(image,"uploadSuccess");
        }
        catch(Exception ex){
            ex.printStackTrace();
            return Json.fail("uploadFailure");
        }
    }
}

